package com.jyy.testpaint;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.pdf.PdfRenderer;
import android.os.Bundle;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private File pdfFile;
    private Thread mThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final File downloadDir = Environment.getExternalStorageDirectory();
        pdfFile = new File(downloadDir, "doc.pdf");

//        createPdf();

        mThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    createPdf();

                    ParcelFileDescriptor fileDescriptor = ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY);
                    final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);

                    // 创建输出目录
                    File outputDir = new File(downloadDir, "output");
                    if (!outputDir.exists()) {
                        outputDir.mkdirs();
                    }

                    for (int i = 0; i < pdfRenderer.getPageCount(); i++) {
                        final PdfRenderer.Page page = pdfRenderer.openPage(i);
                        Bitmap bitmap = Bitmap.createBitmap(page.getWidth(), page.getHeight(), Bitmap.Config.ARGB_8888);
                        page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);

                        // 保存Bitmap为JPG文件
                        File outputFile = new File(outputDir, "page_" + (i + 1) + ".jpg");
                        FileOutputStream out = new FileOutputStream(outputFile);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                        out.flush();
                        out.close();

                        page.close();
                    }

                    pdfRenderer.close();
                    fileDescriptor.close();

                    Log.d(TAG, "转换图片完成.....");

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        mThread.start();
    }

    private void createPdf() {


        final Document document = new Document(PageSize.A4);
        try {
            final PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
            // 添加页面事件处理程序
            pdfWriter.setPageEvent(new PdfPageEventHelper() {
                @Override
                public void onEndPage(PdfWriter writer, Document document) {
                    PdfContentByte canvas = writer.getDirectContentUnder();
                    Rectangle pageSize = document.getPageSize();
                    // 设置背景颜色为白色
                    canvas.setColorFill(com.itextpdf.text.BaseColor.WHITE);
                    canvas.rectangle(pageSize.getLeft(), pageSize.getBottom(),
                            pageSize.getWidth(), pageSize.getHeight());
                    canvas.fill();
                }
            });

            document.open();

            final BaseFont chineseFont = loadChineseFont(this);

            document.addAuthor("");
            document.addCreationDate();
            document.addCreator("");
            document.addTitle("");

//            final Font titleFont = new Font(chineseFont, 24, Font.BOLD, BaseColor.BLACK);
//            final Paragraph title= new Paragraph("Android PDF 文档示例", titleFont);
//            title.setAlignment(Element.ALIGN_CENTER);
//            title.setSpacingAfter(20);
//            document.add(title);
//
//            // 5. 添加副标题
//            Font subtitleFont = new Font(chineseFont, 16, Font.BOLDITALIC, BaseColor.BLUE);
//            Paragraph subtitle = new Paragraph("使用iText 5.5库创建", subtitleFont);
//            subtitle.setAlignment(Element.ALIGN_CENTER);
//            subtitle.setSpacingAfter(30);
//            document.add(subtitle);
//
//            // 6. 添加文本段落
//            Font normalFont = new Font(chineseFont, 12, Font.NORMAL);
//            Paragraph paragraph = new Paragraph();
//            paragraph.add(new Chunk("这是一个使用iText 5.5库创建的PDF文档示例。", normalFont));
//            paragraph.add(Chunk.NEWLINE);
//            paragraph.add(new Chunk("该文档展示了如何在Android应用中生成包含文本、表格和图片的PDF文件。", normalFont));
//            paragraph.setSpacingAfter(20);
//            document.add(paragraph);

            PdfPTable table1 = new PdfPTable(2); // 4列
            table1.setWidthPercentage(100); // 宽度100%
            table1.setSpacingAfter(20);
            table1.setSpacingBefore(20);

            // 表格数据
            String[][] products = {
                    {"编号: 2025120930001", "受理人员: 李梅梅"},
                    {"姓名: 李四", "证件号: 52228199211232048"},
            };

            // 单元格样式
            Font cellFont = new Font(chineseFont, 10);
            PdfPCell cell = new PdfPCell();
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setPadding(5);

            // 添加表格数据
            for (String[] product : products) {
                for (String value : product) {
                    cell.setPhrase(new Phrase(value, cellFont));
                    table1.addCell(cell);
                }
            }
            document.add(table1);


            PdfPTable imageTable = new PdfPTable(2); // 2列表格
            imageTable.setSpacingAfter(20);
            imageTable.setWidthPercentage(100); // 表格宽度100%

            try {
                // 从drawable资源加载图片
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.front_image);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
                byte[] bitmapData = stream.toByteArray();

                Image image = Image.getInstance(bitmapData);
                image.scaleToFit(200, 100);
                image.setAlignment(Image.MIDDLE);
                image.setSpacingAfter(30);

                PdfPCell cell1 = createImageCell(image, "");
                cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
                imageTable.addCell(cell1);

                // 从drawable资源加载图片
                Bitmap bitmap2 = BitmapFactory.decodeResource(getResources(), R.drawable.back_image);
                ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
                bitmap2.compress(Bitmap.CompressFormat.PNG, 50, stream2);
                byte[] bitmapData2 = stream.toByteArray();

                Image image2 = Image.getInstance(bitmapData2);
                image2.scaleToFit(200, 100);
                image2.setAlignment(Image.MIDDLE);
                image2.setSpacingAfter(30);

                PdfPCell cell2 = createImageCell(image2, "");
                cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
                imageTable.addCell(cell2);

                document.add(imageTable);
            } catch (Exception e) {
                Log.e(TAG, "无法添加图片", e);
            }

            Font titleFont = new Font(chineseFont, 14, Font.BOLD, BaseColor.DARK_GRAY);
            Paragraph title = new Paragraph("人证比对记录", titleFont);
            title.setSpacingAfter(10);
            title.setAlignment(Element.ALIGN_LEFT);
            document.add(title);

            PdfPTable table2 = new PdfPTable(5);
            table2.setSpacingAfter(20);
            table2.setWidthPercentage(100);

            Font headerFont = new Font(chineseFont, 12, Font.BOLD, BaseColor.WHITE);
            PdfPCell headerCell = new PdfPCell();
            headerCell.setBackgroundColor(BaseColor.DARK_GRAY);
            headerCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            headerCell.setPadding(8);

            // 添加表头
            String[] headers = new String[]{"对比来源照片", "采集照片", "活体验证", "比对相似度", "比对结果"};
            for (String header : headers) {
                headerCell.setPhrase(new Phrase(header, headerFont));
                table2.addCell(headerCell);
            }

            // 单元格样式
            cellFont = new Font(chineseFont, 10);
            cell = new PdfPCell();
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setPadding(5);

            // 添加头像
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.photo);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
            byte[] bitmapData = stream.toByteArray();

            Image image2 = Image.getInstance(bitmapData);
            image2.scaleToFit(30, 50);
            image2.setAlignment(Image.MIDDLE);


            PdfPCell cell2 = createImageCell(image2, "");
            cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell2.setHorizontalAlignment(Element.ALIGN_CENTER);

            table2.addCell(cell2);

            // 添加现场照片
            bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.photo2);
            stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 40, stream);
            bitmapData = stream.toByteArray();

            image2 = Image.getInstance(bitmapData);
            image2.scaleToFit(30, 50);
            image2.setAlignment(Image.MIDDLE);

            cell2 = createImageCell(image2, "");
            cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell2.setHorizontalAlignment(Element.ALIGN_MIDDLE);

            table2.addCell(cell2);

            cell.setPhrase(new Phrase("开", cellFont));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table2.addCell(cell);

            cell.setPhrase(new Phrase("76.9%", cellFont));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table2.addCell(cell);

            cell.setPhrase(new Phrase("比对通过", cellFont));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table2.addCell(cell);

            document.add(table2);

            // 添加标题
            titleFont = new Font(chineseFont, 14, Font.BOLD, BaseColor.DARK_GRAY);
            title = new Paragraph("人证对比采集照片", titleFont);
            title.setSpacingAfter(10);
            title.setAlignment(Element.ALIGN_LEFT);
            document.add(title);

            // 7. 添加图片
            imageTable = new PdfPTable(1); // 2列表格
            imageTable.setWidthPercentage(100); // 表格宽度100%

            image2 = Image.getInstance(bitmapData);
            image2.setAlignment(Image.MIDDLE);
            imageTable.addCell(image2);

            document.add(imageTable);

            // 11. 关闭文档
            document.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            Log.d(TAG, "生成PDF完成.....");
        }
    }

    // 创建包含图片和标题的单元格
    private static PdfPCell createImageCell(Image image, String caption) {
        // 创建一个容器表格（1列）
        PdfPTable container = new PdfPTable(1);
        container.setWidthPercentage(100);

        // 设置图片大小（保持宽高比）
        float maxWidth = 200f;
        float maxHeight = 150f;
        image.scaleToFit(maxWidth, maxHeight);

        // 添加图片到单元格
        PdfPCell imageCell = new PdfPCell(image, true);
        imageCell.setBorder(Rectangle.NO_BORDER);
        imageCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        container.addCell(imageCell);

        // 添加标题
        Font captionFont = new Font(Font.FontFamily.HELVETICA, 10, Font.ITALIC, BaseColor.DARK_GRAY);
        PdfPCell captionCell = new PdfPCell(new Phrase(caption, captionFont));
        captionCell.setBorder(Rectangle.NO_BORDER);
        captionCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        captionCell.setPaddingTop(5);
        container.addCell(captionCell);

        // 创建外部单元格包含整个容器
        PdfPCell outerCell = new PdfPCell(container);
        outerCell.setPadding(10);
        outerCell.setBorder(Rectangle.BOX); // 添加边框
        outerCell.setBorderColor(BaseColor.LIGHT_GRAY);
        outerCell.setBackgroundColor(new BaseColor(245, 245, 245)); // 浅灰色背景

        return outerCell;
    }

    // 加载中文字体
    private static BaseFont loadChineseFont(Context context) throws DocumentException, IOException {
        AssetManager assetManager = context.getAssets();
        InputStream fontStream = null;
        FileOutputStream out = null;
        final String fontsDir = Environment.getExternalStorageDirectory() + "/fonts";
        try {
            // 尝试加载字体文件 - 根据你的字体文件修改名称
            String[] possibleFonts = {
                    "simhei.ttf",               // 黑体
            };

            for (String fontPath : possibleFonts) {
                try {
                    fontStream = assetManager.open(fontPath);
                    String outFile = fontsDir + "/" + fontPath;
                    out = new FileOutputStream(outFile);
                    copyFile(fontStream, out);

                    // 加载字体并支持中文
                    return BaseFont.createFont(outFile, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                } catch (IOException e) {
                    // 尝试下一个字体
                    Log.w(TAG, "字体未找到: " + fontPath);
                    if (fontStream != null) {
                        try {
                            fontStream.close();
                        } catch (IOException ex) {
                            Log.e(TAG, "关闭字体流失败", ex);
                        }
                    }
                }
            }

            // 如果所有字体都找不到，使用系统默认（可能不支持中文）
            Log.w(TAG, "未找到中文字体，使用默认字体（可能无法显示中文）");
            return BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
        } finally {
            if (fontStream != null) {
                try {
                    fontStream.close();
                } catch (IOException e) {
                    Log.e(TAG, "关闭字体流失败", e);
                }
            }
        }
    }

    private static void copyFile(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
    }
}